<script setup lang="ts">
import { getHomeBanner, getHomeCategory, getHot } from '@/services/home'
import CustomNarbar from './components/CustomNarbar.vue'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import type { XtxGuessInstance } from '@/types/component'
import IndexSkeleton from './components/IndexSkeleton.vue'

const bannerList = ref<BannerItem[]>([])
const categoryList = ref<CategoryItem[]>([])
const hotList = ref<HotItem[]>([])

const getHomeBannerData = async () => {
  console.log('getHomeBannerData')
  const res = await getHomeBanner()
  console.log(res)
  bannerList.value = res.result
}

const getHomeCategoryData = async () => {
  console.log('getCategory')
  const res = await getHomeCategory()
  console.log(res)
  categoryList.value = res.result
}

const getHotData = async () => {
  console.log('getHot')
  const res = await getHot()
  console.log(res)
  hotList.value = res.result
}

const guessRef = ref<XtxGuessInstance>()

/**
 * 滚动到底部 事件 分页加载更多的数据
 */
const onScrollToLower = () => {
  console.log('onScrollToLower')
  guessRef.value?.getMore()
}
// 下拉刷新动画的关闭
const trigger = ref(false)

/**
 * 下拉刷新触发事件
 */
const onRefreshRefresh = async () => {
  trigger.value = true
  try {
    // 重置猜你喜欢的数据
    guessRef.value?.reset()
    // 同时请求数据
    await Promise.all([
      getHomeBannerData(),
      getHomeCategoryData(),
      getHotData(),
      guessRef.value?.getMore(),
    ])
  } finally {
    trigger.value = false
  }
}

const onLoaded = ref(false)

onLoad(async () => {
  onLoaded.value = true
  try {
    // 重置猜你喜欢的数据
    await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHotData()])
  } finally {
    onLoaded.value = false
  }
})
</script>

<template>
  <CustomNarbar />
  <scroll-view
    refresher-enabled
    :refresher-triggered="trigger"
    @refresherrefresh="onRefreshRefresh"
    scroll-y
    class="scroll-view"
    @scrolltolower="onScrollToLower"
  >
    <IndexSkeleton v-if="onLoaded" />

    <template v-else>
      <XtxSwiper :list="bannerList" />
      <CategoryPanel :list="categoryList" />
      <HotPanel :list="hotList" />
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;

  .scroll-view {
    flex: 1;
  }
}
</style>
